'use client';

import type { ISectionClient, ITag } from '@/interfaces';
import Image from 'next/image';
import classNames from 'classnames';
import Link from 'next/link';
import type { MouseEvent } from 'react';
import { useContext } from 'react';
import { getCover, getQueryStrings } from '@/lib/tool';
import { useRouter, useSearchParams } from 'next/navigation';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import { HomePageContext } from '@/contexts/home';
import { AppContext } from '@/contexts/app';

export default function SectionHomeH5Page(this: any) {
  const {
    source: {
      sections,
      sectionDetails,
      queryParams: { sectionGroupId, tagId },
    },
    translatedFields,
  } = useContext(HomePageContext)!;
  const appContext = useContext(AppContext);
  const metadata = appContext.metadata!;
  const env = metadata!.env;
  const router = useRouter();
  const searchParams = useSearchParams();
  const currentSectionItem = sectionDetails?.basic;
  const items = sections.filter((item) =>
    sectionGroupId && item.sectionGroup
      ? sectionGroupId === item.sectionGroup.id + ''
      : true,
  );
  const tags = sectionDetails?.tags ?? [];
  const currentTagItem = tags.find((item) => item.id + '' === tagId);

  function onClickSectionItem(item: ISectionClient) {
    let url;
    if (currentSectionItem) {
      url = `?${getQueryStrings({}, searchParams, ['sectionId', 'sid'], true)}`;
    } else {
      url = `?${getQueryStrings(
        {
          sid: item.id,
        },
        searchParams,
      )}`;
    }
    router.push(url);
  }

  function onClickTagItem(item: ITag, e: MouseEvent<HTMLLIElement>) {
    e.stopPropagation();
    e.preventDefault();

    let url;
    if (currentTagItem) {
      url = `?${getQueryStrings({}, searchParams, ['tagId', 'tid'], true)}`;
    } else {
      url = `?${getQueryStrings(
        {
          tid: item.id,
        },
        searchParams,
      )}`;
    }
    router.push(url);
  }

  return (
    <div className="vstack gap-3">
      <div className="hstack gap-4 align-items-center justify-content-between">
        <div className="h4 mb-0">{translatedFields.allContent}</div>
        <Link
          className={classNames(
            'text-decoration-none',
            items.length === 0 ? 'text-secondary' : 'text-reset',
          )}
          href="/sections"
        >
          {translatedFields.more}
          <i className="bi bi-chevron-right"></i>
        </Link>
      </div>
      <div className="pb-2 hstack gap-4 flex-nowrap text-nowrap overflow-x-auto">
        {items.map((item) => {
          return (
            <div
              key={item.id}
              onClick={onClickSectionItem.bind(this, item)}
              className={classNames(
                'rounded-4 p-3 vstack gap-2 flex-shrink-0 cursor-pointer',
                currentSectionItem?.id === item.id
                  ? 'bg-secondary-subtle'
                  : 'bg-body-tertiary',
              )}
              style={{ width: 260, height: 260 }}
            >
              {item.cover ? (
                <>
                  <div className="flex-grow-1 rounded-3 position-relative">
                    <Image
                      className="rounded-3 object-fit-contain w-auto"
                      src={getCover(item.cover, metadata)!}
                      alt="cover"
                      fill
                      placeholder="blur"
                      blurDataURL={env.APP_BLUR_DATA_URL}
                      sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                    />
                  </div>
                  <div
                    className={classNames('pt-2 flex-shrink-0 text-truncate', {
                      'link-primary':
                        currentTagItem && currentSectionItem?.id === item.id,
                    })}
                  >
                    {item.name}
                  </div>
                </>
              ) : (
                <div className="m-auto">{item.name}</div>
              )}

              <nav aria-label="tag">
                <ol className="pb-2 breadcrumb mb-0 d-flex flex-nowrap text-nowrap overflow-x-auto">
                  {item.tags.map((tagItem) => {
                    return (
                      <li
                        key={tagItem.id}
                        onClick={onClickTagItem.bind(this, tagItem)}
                        className={classNames(
                          'breadcrumb-item flex-shrink-0',
                          currentTagItem?.id === tagItem.id &&
                            currentSectionItem?.id === item.id
                            ? 'active'
                            : 'link-primary',
                        )}
                      >
                        <i className="bi bi-tag me-1"></i>
                        <span>{tagItem.name}</span>
                      </li>
                    );
                  })}
                </ol>
              </nav>
            </div>
          );
        })}
      </div>
      {items.length === 0 && <Nodata />}
    </div>
  );
}
